/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openFuyao is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package query

import (
	"os"
	"path/filepath"
	"testing"

	"env-check/pkg/config"
	"env-check/pkg/logger"
)

func TestQueryExecuteBasic(t *testing.T) {
	tempDir := setupTestDir(t)
	defer os.RemoveAll(tempDir)

	cfg := createTestConfig(tempDir)
	log := logger.NewLogger("")
	q := NewQuery(cfg, log)

	result, err := q.Execute()
	assertNoError(t, err)
	assertEqual(t, len(result.Files), 1)
	assertEqual(t, result.Files[0].Exists, true)
}

func TestQueryExecuteNonExistentPath(t *testing.T) {
	cfg := &config.AppConfig{
		Mode:  config.ModeQuery,
		Paths: []string{"/non/existent/path"},
	}
	log := logger.NewLogger("")
	q := NewQuery(cfg, log)

	result, err := q.Execute()
	assertNoError(t, err)
	assertEqual(t, len(result.Files), 1)
	assertEqual(t, result.Files[0].Exists, false)
}

func TestQueryPathFile(t *testing.T) {
	tempDir := setupTestDir(t)
	defer os.RemoveAll(tempDir)

	cfg := createTestConfig(tempDir)
	log := logger.NewLogger("")
	q := NewQuery(cfg, log)

	fileInfo := q.queryPath(tempDir)
	assertEqual(t, fileInfo.Exists, true)
	assertEqual(t, fileInfo.IsDir, true)
}

func TestQueryPathNonExistent(t *testing.T) {
	cfg := createTestConfig("")
	log := logger.NewLogger("")
	q := NewQuery(cfg, log)

	fileInfo := q.queryPath("/non/existent/path")
	assertEqual(t, fileInfo.Exists, false)
	assertNotEqual(t, fileInfo.Error, "")
}

// 辅助函数
func setupTestDir(t *testing.T) string {
	tempDir, err := os.MkdirTemp("", "query-test-*")
	assertNoError(t, err)

	testFile := filepath.Join(tempDir, "test.txt")
	err = os.WriteFile(testFile, []byte("test content"), config.FileMode)
	assertNoError(t, err)

	return tempDir
}

func createTestConfig(path string) *config.AppConfig {
	return &config.AppConfig{
		Mode:  config.ModeQuery,
		Paths: []string{path},
	}
}

func assertNotEqual(t *testing.T, actual, expected interface{}) {
	t.Helper()
	if actual == expected {
		t.Fatalf("Expected not equal, but both are %v", actual)
	}
}

func assertEqual(t *testing.T, actual, expected interface{}) {
	t.Helper()
	if actual != expected {
		t.Fatalf("Expected %v, got %v", expected, actual)
	}
}

// AssertNoError 检查没有错误
func assertNoError(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatalf("Expected no error, got: %v", err)
	}
}
